﻿using RotovapPlatform.Domain.Equipment.Interfaces.Services;
using RotovapPlatform.Domain.Equipment.Interfaces.Communication;
using Microsoft.Extensions.Logging;
using RotovapPlatform.Domain.Equipment.Interfaces.Base;
using RotovapPlatform.Domain.Equipment.Interfaces.Robot;
using Microsoft.Extensions.DependencyInjection;

namespace RotovapPlatform.Application.Services;

public class DeviceManager : IDeviceManager
{
	private readonly IEtherCATManager _etherCATManager;
	private readonly ISerialServerManager _serialServerManager;
	private readonly IModbusTcpClient _robotModbus;
	private readonly IRobotEM _robot;
	private readonly IMotorControlService _motorControlService; // 添加电机控制服务
	private readonly Dictionary<string, IMotorBase> _motors = new(); // 电机字典保留作为备用
	private readonly Dictionary<string, IPumpBase> _pumps = new(); // 泵字典
	private readonly Dictionary<string, ITCUBase> _tcus = new();
	private readonly Dictionary<string, IOilBathBase> _oilBaths = new(); // 油浴锅字典
	private readonly Dictionary<string, ITemperatureCollectorBase> _temperatureCollectors = new(); // 温度采集模块字典
	private readonly Dictionary<string, IValveBase> _valves = new(); // 切换阀字典
	private readonly ILogger<DeviceManager> _logger;
	private readonly IServiceProvider _serviceProvider; // 添加服务提供者
	private bool _isInitialized;


	public DeviceManager(
		IEtherCATManager etherCATManager,
		ISerialServerManager serialServerManager,
		IModbusTcpClient robotModbus,
		IEnumerable<IMotorBase> motors,
		IEnumerable<IPumpBase> pumps,
		IEnumerable<ITCUBase> tcus,
		IEnumerable<IOilBathBase> oilBaths, // 添加油浴锅参数
		IEnumerable<ITemperatureCollectorBase> temperatureCollectors, // 添加温度采集模块参数
		IEnumerable<IValveBase> valves, // 添加切换阀参数
		IRobotEM robot,
		IMotorControlService motorControlService, // 注入电机控制服务
		ILogger<DeviceManager> logger,
		IServiceProvider serviceProvider) // 注入服务提供者
	{
		_etherCATManager = etherCATManager;
		_serialServerManager = serialServerManager;
		_robotModbus = robotModbus;
		_robot = robot;
		_motorControlService = motorControlService;
		_logger = logger;
		_serviceProvider = serviceProvider;

		// 初始化电机字典
		if (motors != null)
		{
			foreach (var motor in motors)
			{
				if (!string.IsNullOrEmpty(motor.EquipmentId))
				{
					_motors[motor.EquipmentId] = motor;
				}
			}
		}

		// 初始化泵和TCU字典
		if (pumps != null)
		{
			foreach (var pump in pumps)
			{
				if (!string.IsNullOrEmpty(pump.EquipmentId))
				{
					_pumps[pump.EquipmentId] = pump;
				}
			}
		}

		if (tcus != null)
		{
			foreach (var tcu in tcus)
			{
				if (!string.IsNullOrEmpty(tcu.EquipmentId))
				{
					_tcus[tcu.EquipmentId] = tcu;
				}
			}
		}

		// 初始化油浴锅字典
		if (oilBaths != null)
		{
			foreach (var oilBath in oilBaths)
			{
				if (!string.IsNullOrEmpty(oilBath.EquipmentId))
				{
					_oilBaths[oilBath.EquipmentId] = oilBath;
					_logger.LogInformation($"已加载油浴锅设备: {oilBath.EquipmentId}");
				}
			}
		}

		// 初始化温度采集模块字典
		if (temperatureCollectors != null)
		{
			foreach (var collector in temperatureCollectors)
			{
				if (!string.IsNullOrEmpty(collector.EquipmentId))
				{
					_temperatureCollectors[collector.EquipmentId] = collector;
					_logger.LogInformation($"已加载温度采集模块: {collector.EquipmentId}");
				}
			}
		}

		// 初始化切换阀字典
		if (valves != null)
		{
			foreach (var valve in valves)
			{
				if (!string.IsNullOrEmpty(valve.EquipmentId))
				{
					_valves[valve.EquipmentId] = valve;
					_logger.LogInformation($"已加载切换阀设备: {valve.EquipmentId}");
				}
			}
		}
	}

	public async Task<bool> InitializeAsync()
	{
		try
		{
			// 第一步：初始化轴卡
			var initialResult = await _etherCATManager.ConnectAsync();
			if (!initialResult) return false;

			// 注意：不再重复初始化电机控制服务，因为App.xaml.cs中已经进行了初始化
			// 仅记录日志说明这一点
			_logger.LogInformation("电机控制服务已在应用启动时初始化，此处跳过重复初始化");

			// 加载电机设备(保持原有代码，确保兼容性)
			var motorDrives = _serviceProvider.GetServices<IMotorBase>();
			foreach (var motor in motorDrives)
			{
				_motors[motor.EquipmentId] = motor;
				_logger.LogInformation($"已加载电机设备: {motor.EquipmentId}");
			}

			// 加载切换阀设备(直连串口方式，不依赖串口服务器)
			var valveDrives = _serviceProvider.GetServices<IValveBase>();
			foreach (var valve in valveDrives)
			{
				_valves[valve.EquipmentId] = valve;
				_logger.LogInformation($"已加载切换阀设备: {valve.EquipmentId}");
			}

			// 初始化串口服务器
			var connectResult = await _serialServerManager.ConnectAsync();
			if (!connectResult)
			{
				_logger.LogWarning("串口服务器连接失败，部分设备可能无法正常工作");
			}
			else
			{
				_logger.LogInformation("串口服务器连接成功");

				//加载TCU
				var tcuDrives = _serviceProvider.GetServices<ITCUBase>();
				foreach (var tcu in tcuDrives)
				{
					_tcus[tcu.EquipmentId] = tcu;
					_logger.LogInformation($"已加载TCU设备: {tcu.EquipmentId}");
				}

				// 加载油浴锅和温度采集模块
				var oilBathDrives = _serviceProvider.GetServices<IOilBathBase>();
				foreach (var oilBath in oilBathDrives)
				{
					_oilBaths[oilBath.EquipmentId] = oilBath;
					_logger.LogInformation($"已加载油浴锅设备: {oilBath.EquipmentId}");
				}

				var temperatureCollectorDrives = _serviceProvider.GetServices<ITemperatureCollectorBase>();
				foreach (var collector in temperatureCollectorDrives)
				{
					_temperatureCollectors[collector.EquipmentId] = collector;
					_logger.LogInformation($"已加载温度采集模块: {collector.EquipmentId}");
				}
			}

			// 第三步：原有机器人初始化逻辑
			return await InitializeRobotAsync();
		}
		catch (Exception ex)
		{
			_logger.LogError(ex, "设备初始化失败");
			return false;
		}
	}

	private async Task<bool> InitializeRobotAsync()
	{
		try
		{
			// 增加连接验证
			if (!await _robotModbus.ConnectAsync() ||
				_robotModbus.Master == null)
			{
				_logger.LogError("ModbusTCP连接初始化失败");
				return false;
			}

			// 发送测试指令验证连接
			var testResult = await _robotModbus.ReadInputRegistersAsync(
				1, 96, 1);

			return testResult.Length > 0;
		}
		catch (Exception ex)
		{
			_logger.LogError(ex, "连接初始化过程中发生错误");
			return false;
		}
	}

	// 获取设备实例的方法
	public IMotorBase GetMotor(string motorId)
	{
		try
		{
			// 优先使用电机控制服务
			return _motorControlService.GetMotorAsync(motorId).GetAwaiter().GetResult();
		}
		catch (Exception exService)
		{
			_logger.LogWarning(exService, $"从电机控制服务获取电机 {motorId} 失败，尝试从内部字典获取");

			// 如果电机控制服务获取失败，尝试从内部字典获取
			if (_motors.TryGetValue(motorId, out var motor))
			{
				return motor;
			}

			// 都失败则抛出异常
			throw new KeyNotFoundException($"未找到电机: {motorId}");
		}
	}

	public IPumpBase GetPump(string pumpId) =>
		_pumps.GetValueOrDefault(pumpId) ?? throw new KeyNotFoundException($"未找到泵: {pumpId}");

	public ITCUBase GetTCU(string tcuId) => _tcus.GetValueOrDefault(tcuId);

	// 获取油浴锅实例
	public IOilBathBase GetOilBath(string oilBathId) =>
		_oilBaths.GetValueOrDefault(oilBathId) ?? throw new KeyNotFoundException($"未找到油浴锅: {oilBathId}");

	// 获取温度采集模块实例
	public ITemperatureCollectorBase GetTemperatureCollector(string collectorId) =>
		_temperatureCollectors.GetValueOrDefault(collectorId) ?? throw new KeyNotFoundException($"未找到温度采集模块: {collectorId}");

	// 获取切换阀实例
	public IValveBase GetValve(string valveId) =>
		_valves.GetValueOrDefault(valveId) ?? throw new KeyNotFoundException($"未找到切换阀: {valveId}");

	public async Task<bool> ShutdownAsync()
	{
		try
		{
			_logger.LogInformation("开始关闭设备...");

			// 关闭所有电机 - 首先尝试使用电机控制服务
			try
			{
				_logger.LogInformation("使用电机控制服务关闭所有电机");
				var motors = await _motorControlService.GetMotorsAsync();
				foreach (var motor in motors)
				{
					try
					{
						await _motorControlService.DisableMotorAsync(motor.EquipmentId);
						_logger.LogInformation($"电机 {motor.Name} 已禁用");
					}
					catch (Exception ex)
					{
						_logger.LogError(ex, $"使用电机控制服务关闭电机 {motor.Name} 失败");
					}
				}
			}
			catch (Exception ex)
			{
				_logger.LogWarning(ex, "使用电机控制服务关闭电机失败，尝试使用内部电机字典");

				// 如果电机控制服务失败，回退到直接使用电机字典
				foreach (var motor in _motors.Values)
				{
					try
					{
						await motor.DisableAsync();
						_logger.LogInformation($"使用内部字典关闭电机 {motor.Name} 成功");
					}
					catch (Exception motorEx)
					{
						_logger.LogError(motorEx, $"关闭电机 {motor.Name} 失败");
					}
				}
			}

			// 关闭所有泵
			foreach (var pump in _pumps.Values)
			{
				try
				{
					await pump.DisableAsync();
				}
				catch (Exception ex)
				{
					_logger.LogError(ex, $"关闭泵 {pump.Name} 失败");
				}
			}

			// 关闭所有TCU
			foreach (var tcu in _tcus.Values)
			{
				try
				{
					await tcu.PowerSwitchAsync(false);
				}
				catch (Exception ex)
				{
					_logger.LogError(ex, $"关闭TCU {tcu.Name} 失败");
				}
			}

			// 关闭所有油浴锅
			foreach (var oilBath in _oilBaths.Values)
			{
				try
				{
					await oilBath.SetRunningStatusAsync(2); // 关闭油浴锅运行
					_logger.LogInformation($"油浴锅 {oilBath.Name} 已关闭");
				}
				catch (Exception ex)
				{
					_logger.LogError(ex, $"关闭油浴锅 {oilBath.Name} 失败");
				}
			}

			// 关闭所有切换阀（切换到通道0作为安全位置）
			foreach (var valve in _valves.Values)
			{
				try
				{
					await valve.SwitchToChannelAsync(0); // 切换到通道0
					_logger.LogInformation($"切换阀 {valve.Name} 已设置为安全位置");

					// 释放切换阀占用的COM端口资源
					if (valve is IDisposable disposableValve)
					{
						disposableValve.Dispose();
						_logger.LogInformation($"切换阀 {valve.Name} 资源已释放");
					}
				}
				catch (Exception ex)
				{
					_logger.LogError(ex, $"关闭切换阀 {valve.Name} 失败");
				}
			}

			// 关闭机器人
			try
			{
				await _robotModbus.DisconnectAsync();
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "关闭机器人失败");
			}

			// 关闭通信
			await _serialServerManager.DisconnectAsync();
			await _robotModbus.DisconnectAsync();

			_logger.LogInformation("所有设备已关闭");
			return true;
		}
		catch (Exception ex)
		{
			_logger.LogError(ex, "关闭设备过程中发生错误");
			return false;
		}
	}


	// 提供设备集合的只读访问
	public IReadOnlyDictionary<string, IMotorBase> Motors
	{
		get
		{
			try
			{
				// 优先尝试从电机控制服务获取
				var motors = _motorControlService.GetMotorsAsync().GetAwaiter().GetResult();
				return motors.ToDictionary(m => m.EquipmentId);
			}
			catch (Exception ex)
			{
				_logger.LogWarning(ex, "从电机控制服务获取电机字典失败，使用内部字典");
				// 如果失败，回退到内部字典
				return _motors;
			}
		}
	}
	public IReadOnlyDictionary<string, IPumpBase> Pumps => _pumps;
	public IReadOnlyDictionary<string, ITCUBase> TCUs => _tcus;
	public IReadOnlyDictionary<string, IOilBathBase> OilBaths => _oilBaths; // 暴露油浴锅字典
	public IReadOnlyDictionary<string, ITemperatureCollectorBase> TemperatureCollectors => _temperatureCollectors; // 暴露温度采集模块字典
	public IReadOnlyDictionary<string, IValveBase> Valves => _valves; // 暴露切换阀字典

	public IRobotEM Robot => _robot;


	public async Task<bool> UpdateAllAxisStatusAsync()
	{
		return await _etherCATManager.GetAllAxisStatusAsync();
	}
}
